<template>
    <AppTitle title="添加商品"></AppTitle>
    <div class="addBox">
        <el-form
        :model="productForm"
        :rules="rules"
        ref="productFormRef"
        label-width="100px"
        class="product-form"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="productForm.category" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="productForm.price" 
            :min="0" 
            :precision="2"
            :step="0.1"
          />
        </el-form-item>
        
        <el-form-item label="商品库存" prop="stock">
          <el-input-number 
            v-model="productForm.stock" 
            :min="0"
            :step="1"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="imgUrl">
          <el-upload
            class="upload-demo"
            action="/api/goods/goods_img_upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
          <img v-if="imageUrl" :src="'/api'+imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" prop="goodsDesc">
          <el-input
            v-model="productForm.goodsDesc"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        
        <el-form-item label="商品详情" prop="detail">
          <div class="editor-container">
            <el-input
              v-model="productForm.detail"
              type="textarea"
              :rows="6"
              style="width: 400px;"
              placeholder="请输入商品详情"
            />
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { goodsAdd, goodsCatelist } from '@/api/goods.js'

const router = useRouter()
const productFormRef = ref(null)
const fileList = ref([])
// 模拟分类数据
const categories = ref([])
const imageUrl = ref('')
const productForm = ref({
  name: '',
  category: '',
  price: 0,
  stock: 0,
  imgUrl: '',
  goodsDesc: '',
  detail: ''
})

const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ]
}

const handlePreview = (file) => {
  console.log('预览文件:', file)
}

const getlist = async () => {
  const { data } = await goodsCatelist({ currentPage: 1, pageSize: 50 })
  categories.value = data.filter(item => item.state === 1).map(item => ({ name: item.cateName }))
}

onMounted(() => {
  getlist()
  setTimeout(() => {
    if (productFormRef.value) {
      productFormRef.value.$el.classList.add('loaded')
    }
  }, 100)
})

const handleRemove = (file, fileList) => {
  console.log('移除文件:', file, fileList)
}

const beforeRemove = (file) => {
  return ElMessageBox.confirm(
    `确定移除 ${file.name}？`,
    '提示',
    { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  )
}

const handleAvatarSuccess = (response, file, fileList) => {
  ElMessage.success('上传成功')
  productForm.value.imgUrl = response.imgUrl.slice(23, response.imgUrl.length);
  imageUrl.value = response.imgUrl
  console.log(imageUrl.value);
  
}
const beforeAvatarUpload = (rawFile) => {
        if (rawFile.type !== 'image/jpeg') {
            ElMessage.error('请上传图片');
            return false;
        } else if (rawFile.size / 1024 / 1024 > 10) {
            ElMessage.error('图片大小不能超过 10MB!');
            return false;
        }
        return true;
    };


const submitLoading = ref(false)
const handleSubmit = async () => {
  submitLoading.value = true
  const valid = await productFormRef.value.validate()
  if (!valid) {
    // 触发抖动动画
    const errorInputs = document.querySelectorAll('.is-error')
    errorInputs.forEach(input => {
      input.classList.add('shake-animation')
      setTimeout(() => input.classList.remove('shake-animation'), 300)
    })
    submitLoading.value = false
    return
  }
  try {
    const res = await goodsAdd(productForm.value)
    if (res.code === 0) {
      ElMessage.success('添加成功')
      router.push('/goodsList')
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    ElMessage.error('提交出现错误，请稍后重试')
    console.error('提交错误:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleCancel = () => {
  router.push('/goodsList')
}    

</script>

<style scoped>
/* 表单元素入场动画 */
.product-form .el-form-item {
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.5s cubic-bezier(0.075, 0.82, 0.165, 1) 0.1s;
}

.product-form .el-form-item:nth-child(1) { transition-delay: 0.1s; }
.product-form .el-form-item:nth-child(2) { transition-delay: 0.2s; }
.product-form .el-form-item:nth-child(3) { transition-delay: 0.3s; }
.product-form .el-form-item:nth-child(4) { transition-delay: 0.4s; }
.product-form .el-form-item:nth-child(5) { transition-delay: 0.5s; }
.product-form .el-form-item:nth-child(6) { transition-delay: 0.6s; }
.product-form .el-form-item:nth-child(7) { transition-delay: 0.7s; }
.product-form .el-form-item:nth-child(8) { transition-delay: 0.8s; }

/* 加载时显示表单元素 */
.product-form.loaded .el-form-item {
  opacity: 1;
  transform: translateY(0);
}
.avatar{
    width: 100px;
    height: 100px;
}
/* 输入框验证错误动画 */
:deep(.el-input__wrapper.is-error) {
  animation: shake 0.3s ease-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

/* 分类选项悬停动画 */
:deep(.el-select__item:hover) {
  background-color: #f0f5ff;
  transform: translateX(8px);
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(100, 108, 255, 0.1);
}

/* 上传图片预览动画 */
:deep(.el-upload-list__item-preview) {
  transition: transform 0.3s ease;
}

:deep(.el-upload-list__item-preview:hover) {
  transform: scale(1.05);
  z-index: 10;
}

/* 按钮加载状态动画 */
:deep(.el-button--primary.loading) {
  opacity: 0.8;
  pointer-events: none;
}

:deep(.el-button--primary.loading::after) {
  content: '';
  display: inline-block;
  margin-left: 12px;
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top-color: #fff;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 响应式切换动画 */
:deep(.el-form-item.button-group) {
  transition: all 0.3s ease;
}

/* 全局点击涟漪效果 */
:deep(.el-ripple) {
  animation-name: ripple;
  animation-duration: 0.6s;
  animation-timing-function: cubic-bezier(0.2, 0.8, 0.2, 1);
}

@keyframes ripple {
  0% {
    transform: scale(0.1);
    opacity: 1;
  }
  100% {
    transform: scale(2);
    opacity: 0;
  }
}
</style>